package com.laicunba.service.accounting.impl;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.laicunba.service.AlertService;
import com.laicunba.service.CurrentAccountService;
import com.laicunba.service.FinancingTargetBidService;
import com.laicunba.service.WithdrawService;
import com.laicunba.service.WithdrawService.SCBWithdrawResult;
import com.laicunba.service.accounting.InitCurrentAccountService;
import com.laicunba.service.profit.SuiCunBaoProfitService;
import com.laicunba.service.profit.SuiCunBaoProfitService.MergedProfitResult;
import com.laicunba.util.AssertUtil;

@Service
public class InitCurrentAccountServiceImpl implements InitCurrentAccountService {
	private static final Logger LOG = Logger.getLogger(InitCurrentAccountServiceImpl.class);
	private static final MathContext mc = new MathContext(10, RoundingMode.HALF_DOWN);
	@Autowired
	private AlertService alertService;
	@Autowired
	private CurrentAccountService currentAccountService;
	@Autowired
	private WithdrawService withdrawService;
	@Autowired
	private SuiCunBaoProfitService suiCunBaoProfitService;

	@Transactional
	@Override
	public boolean doInitAndTransferBidSCB2CurrentAccount(String uid) {
		AssertUtil.assertTrue(currentAccountService.createAccount(uid), "CREATE_CURRENT_ACCOUNT_FAIL");
		MergedProfitResult mergedProfitResult = suiCunBaoProfitService.getMergedProfit(uid);
		BigDecimal allSCBMoney = mergedProfitResult.getPrincipal().add(mergedProfitResult.getTotalProfit(), mc).setScale(2, RoundingMode.DOWN);
		if (allSCBMoney.compareTo(BigDecimal.ZERO) <= 0) {
			LOG.info(String.format("tag:init_current_account_and_transfer_bidscb,uid:%s,balance:0", uid));
			return true;
		}
		// 自动申请
		WithdrawService.SCBWithdrawParam apply = new WithdrawService.SCBWithdrawParam();
		apply.setTry(false);
		apply.setUserId(uid);
		apply.setWithdrawAmount(allSCBMoney);
		apply.setMark("INIT_CURRENT_ACCOUNT");
		SCBWithdrawResult applyResult = withdrawService.doWithDrawApply(apply);
		// 自动确认
		WithdrawService.DoWithdrawParam param = new WithdrawService.DoWithdrawParam();
		param.setWidthdrawId(applyResult.getWithdrawId());
		AssertUtil.assertTrue(withdrawService.doWithDraw(param), "DO_WITHDRAW_FAIL");
		// 自动存入
		currentAccountService.add(uid, allSCBMoney, "SCB2CA", "初始化并转入");

		LOG.info(String.format("tag:init_current_account_and_transfer_bidscb,uid:%s,balance:%s", uid, allSCBMoney));
		return true;
	}
}
